package com.ltx.admin.service.Impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ltx.admin.common.constant.RedisCacheConstant;
import com.ltx.admin.common.convention.exception.ClientException;
import com.ltx.admin.common.enums.UserErrorCodeEnum;
import com.ltx.admin.dao.entity.UserDo;
import com.ltx.admin.dao.mapper.UserMapper;
import com.ltx.admin.dto.req.UserLoginReqDTO;
import com.ltx.admin.dto.req.UserRegisterReqDTO;
import com.ltx.admin.dto.req.UserUpdateReqDTO;
import com.ltx.admin.dto.resp.UserLoginRespDTO;
import com.ltx.admin.dto.resp.UserRespDTO;
import com.ltx.admin.service.UserService;
import com.ltx.admin.util.BeanUtil;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/*
 * @description 用户接口层实现类
 * @author 罗添煦
 * @create 2024-10-13 下午8:25
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDo> implements UserService {

    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;

    private final StringRedisTemplate stringRedisTemplate;

    private final RedissonClient redissonClient;

    @Override
    public UserRespDTO getUserByUserName(String username) {
        LambdaQueryWrapper<UserDo> queryWrapper = Wrappers.lambdaQuery(UserDo.class)
                .eq(UserDo::getUsername, username);
        UserDo userDo = baseMapper.selectOne(queryWrapper);
        if (userDo == null) {
            throw new ClientException(UserErrorCodeEnum.USER_NULL);
        }
        return BeanUtil.convert(userDo, new UserRespDTO());
    }

    @Override
    public Boolean hasUserName(String username) {
        return !userRegisterCachePenetrationBloomFilter.contains(username);
    }

    @Override
    public void register(UserRegisterReqDTO userRegisterReqDTO) {
        if (!hasUserName(userRegisterReqDTO.getUsername())) {
            throw new ClientException(UserErrorCodeEnum.USER_NAME_EXIST);
        }
        RLock lock = redissonClient.getLock(RedisCacheConstant.LOCK_USER_REGISTER_KEY + userRegisterReqDTO.getUsername());
        try {
            if (lock.tryLock()) {
                // 新增用户数据
                int insert = baseMapper.insert(BeanUtil.convert(userRegisterReqDTO, new UserDo()));
                // 插入失败
                if (insert < 1) {
                    throw new ClientException(UserErrorCodeEnum.USER_SAVE_ERROR);
                }
                userRegisterCachePenetrationBloomFilter.add(userRegisterReqDTO.getUsername());
            } else {
                throw new ClientException(UserErrorCodeEnum.USER_EXIST);
            }
        } finally {
            lock.unlock();
        }
    }

    @Override
    public void update(UserUpdateReqDTO userUpdateReqDTO) {
        // TODO 判断是否为当前登录用户
        LambdaUpdateWrapper<UserDo> wrapper = Wrappers.lambdaUpdate(UserDo.class)
                .eq(UserDo::getUsername, userUpdateReqDTO.getUsername());
        baseMapper.update(cn.hutool.core.bean.BeanUtil.toBean(userUpdateReqDTO, UserDo.class), wrapper);
    }

    @Override
    public UserLoginRespDTO login(UserLoginReqDTO userLoginReqDTO) {
        LambdaUpdateWrapper<UserDo> wrapper = Wrappers.lambdaUpdate(UserDo.class)
                .eq(UserDo::getUsername, userLoginReqDTO.getUsername())
                .eq(UserDo::getPassword, userLoginReqDTO.getPassword())
                .eq(UserDo::getDelFlag, 0);
        UserDo userDo = baseMapper.selectOne(wrapper);
        if (userDo == null) {
            throw new ClientException(UserErrorCodeEnum.USER_NULL);
        }
        Boolean hasLogin = stringRedisTemplate.hasKey("login_" + userDo.getUsername());
        if (hasLogin != null && hasLogin) {
            throw new ClientException("用户已经登录");
        }
        String uuid = UUID.randomUUID().toString();
        stringRedisTemplate.opsForHash().put("login_" + userDo.getUsername(), uuid, JSON.toJSONString(userDo));
        stringRedisTemplate.expire("login_" + userDo.getUsername(), 30L, TimeUnit.MINUTES);
        return new UserLoginRespDTO(uuid);
    }

    @Override
    public Boolean checkLogin(String username, String token) {
        return stringRedisTemplate.opsForHash().get("login_" + username, token) != null;
    }

    @Override
    public void logout(String username, String token) {
        System.out.println(123);
        if(checkLogin(username,token)){
            System.out.println(1231);
            stringRedisTemplate.delete("login_" + username);
            return;
        }
        System.out.println(123123);
        throw new ClientException("用户Token失效或用户未登录");
    }
}
